import java.io.*;
import java.net.*;

public class FileReceiver {
    private final static int PORT = 7777;
    private final static int BUFFER_SIZE = 1024;

    private final static String FILEPATH = "/Users/linrui/b/";
    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(PORT)) {
            System.out.println("开始监听...");

            while (true) {
                final Socket socket = serverSocket.accept();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        handleClient(socket);
                    }
                }).start();
            }


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void handleClient(Socket socket) {
        try (InputStream is = socket.getInputStream();
             ObjectInputStream ois = new ObjectInputStream(is)) {

            // 接收文件和子文件夹的数量
            int numFiles = ois.readInt();

            for (int i = 0; i < numFiles; i++) {
                receiveFileOrFolder(FILEPATH, ois);
            }

            System.out.println("文件及文件夹接收成功。");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 递归接收文件或文件夹
    private static void receiveFileOrFolder(String currentPath, ObjectInputStream ois) throws IOException {
        String type = ois.readUTF();

        if ("DIRECTORY".equals(type)) {
            // 接收文件夹名称并创建文件夹
            String folderName = ois.readUTF();
            File newFolder = new File(currentPath + folderName);
            System.out.println("接收文件夹："+folderName);
            newFolder.mkdir();

            // 递归接收文件夹内容
            int numChildren = ois.readInt();
            for (int i = 0; i < numChildren; i++) {
                receiveFileOrFolder(newFolder.getPath() + "/", ois);
            }
        } else {
            // 接收文件名称和内容
            String fileName = ois.readUTF();
            long fileSize = ois.readLong();

            File newFile = new File(currentPath + fileName);
            System.out.println("接收文件："+fileName);
            byte[] buffer = new byte[BUFFER_SIZE];
            try (FileOutputStream fos = new FileOutputStream(newFile)) {
                while (fileSize > 0) {
                    int bytesRead = ois.read(buffer, 0, (int) Math.min(buffer.length, fileSize));
                    fos.write(buffer, 0, bytesRead);
                    fileSize -= bytesRead;
                }
            }
        }
    }
}
